<?php

class Admin_galleryController extends Controller{

	public $models = array("Gallery");
	public $layout = false;
	public $secure = true;
	
	private $extensions = array("jpg", "gif", "png", "bmp");
	private $extensions_video = array("flv", "mp4");
	private $thumb_dimensions = array(100,70);
	
	public function __construct() {
		parent::__construct();
	}
	
	public function index() {
		
		$galleries = $this->Gallery->getAll();
		$this->assign("galleries", $galleries);
		
		$this->display("admin/gallery/index.html");
	}
	
	public function edit($id=null) {
		$message_class = $this->session_get("message_class");
		if($message_class=="error") {
			$data = $this->session_get("form_data");
			$this->assign("gallery",$data);
		}else if ($id) {
			$gallery = $this->Gallery->getAll($id);
			$this->assign("gallery", $gallery);
		}
		
		$MAX_FILE_UPLOADS = (int)ini_get("max_file_uploads");
		$MAX_FILE_UPLOADS = $MAX_FILE_UPLOADS>0 ? $MAX_FILE_UPLOADS : 10;
		
		$MAX_UPLOAD_FILESIZE = ini_get("upload_max_filesize");
		$MAX_UPLOAD_FILESIZE = $MAX_UPLOAD_FILESIZE ? $MAX_UPLOAD_FILESIZE : "1M";
		
		$this->assign("MAX_UPLOAD_SIZE",$MAX_UPLOAD_FILESIZE);
		$this->assign("MAX_FILE_UPLOADS",$MAX_FILE_UPLOADS);
		
		$this->display("admin/gallery/edit.html");
		$this->session_set("message","");
		$this->session_set("message_class","");
		$this->session_set("form_data",array());
	}
	
	public function save($id=null) {
		$order = getFromInput("order");
		
		$message = "Galerija je sačuvana";
		$ok = true;
		
		if(!strlen($this->data["title"])) {
			$ok = false;
			$message = "Morate popouniti naslov galerije.";
		}else if(!preg_match('/^\d{2,4}-\d{1,2}-\d{1,2}$/',$this->data["date"])) {
			$ok = false;
			$message = "Datum nije validan.";
		}
		
		if($ok) {
			if($id>0) {
				$this->Gallery->update($this->data, array("id"=>$id));
			}else{
				$id = $this->Gallery->insert($this->data);
			}
			
			$image_dir = $_SERVER['DOCUMENT_ROOT']."/userfiles/gallery/$id";
			$image_dir_t = $_SERVER['DOCUMENT_ROOT']."/userfiles/gallery/$id/thumb";
			
			if (!is_dir($image_dir)) {
				mkdir($image_dir, 0777);
				mkdir($image_dir_t, 0777);
			}elseif(!is_dir($image_dir_t)){
				mkdir($image_dir_t, 0777);
			}
			
			// IMAGES
			$images = $_FILES["file_image"];
			foreach ($images["name"] as $k=>$f) {
				if (!$images["error"][$k] && $this->_isValidImage($f)) {
					$this->_prepareFilename($f);
					
					$destination = "$image_dir/$f";
					$destination_t = "$image_dir_t/$f";
					$source = $images["tmp_name"][$k];
					
					$moved = move_uploaded_file($source, $destination);
					if($moved) {
						image_resize($destination);
						copy($destination, $destination_t);
						image_resize($destination_t, $this->thumb_dimensions, false);
						
						$g_id = $this->Gallery->insert(array("gallery_id"=>$id, "type"=>"image", "src"=>$f, "position"=>count($order)+$k), 1);
						$order[] = $g_id;
					}
					
				}
			}
			
			// VIDEOS
			
			$videos = $_FILES["file_video"];
			$videos_thumbs = $_FILES["file_video_thumb"];
			foreach ($videos["name"] as $k=>$v) {
				if(!$videos["error"][$k] && $this->_isValidVideo($v)) {
					// thumb
					if(!$videos_thumbs["error"][$k] && $this->_isValidImage($videos_thumbs["name"][$k])) {
						$v_t = substr($v,0,strrpos($v,".")).substr($videos_thumbs["name"][$k],strrpos($videos_thumbs["name"][$k],"."));
						$moved = move_uploaded_file($videos_thumbs["tmp_name"][$k], "$image_dir_t/$v_t");
						if($moved) {
							image_resize("$image_dir_t/$v_t", $this->thumb_dimensions, false);
						}
					}
					// video
					$moved = move_uploaded_file($videos["tmp_name"][$k], "$image_dir/$v");
					if ($moved) {
						$g_id = $this->Gallery->insert(array("gallery_id"=>$id, "type"=>"video", "src"=>$v, "thumbnail"=>$v_t, "position"=>count($order)+$k), 1);
						$order[] = $g_id;
					}
				}
			}
			
			$this->Gallery->updatePositions($order);
		}

		$this->session_set("message", $message);
		$this->session_set("message_class", $ok?"ok":"error");
		$this->session_set("form_data", $ok?array():$this->data);
		redirect("/admin#gallery/edit/$id");
	}
	
	public function delete($id) {
		if($id>0) {
			$q = "DELETE FROM gallery WHERE id=$id";
			$this->Gallery->_alter($q);
			$q = "DELETE FROM gallery_items WHERE gallery_id=$id";
			$this->Gallery->_alter($q);
			
			$path = $_SERVER["DOCUMENT_ROOT"]."/userfiles/gallery/$id";
			
			emptydir($path);
			emptydir("$path/thumb");
			
			rmdir("$path/thumb");
			rmdir($path);
		}
		redirect("/admin_gallery");
	}
	
	public function item_delete($id) {
		$status = 0;
		if($id) {
			$status = 1;
			$all = getFromInput("all");
			$type = getFromInput("type");
			
			$this->Gallery->table_index = 1;
			$this->Gallery->order = "id";
			$this->Gallery->order_direction = "asc";
			if($all) {
				$src = $this->Gallery->find(array("gallery_id","src", "thumbnail"), array("gallery_id"=>$id, "type"=>$type), false);
				$q = "DELETE FROM gallery_items WHERE gallery_id=$id AND type='$type'";
			}else{
				$src = array(0=>$this->Gallery->findRow(array("gallery_id","src", "thumbnail"), array("id"=>$id)));
				$q = "DELETE FROM gallery_items WHERE id=$id LIMIT 1";
			}
			
			$ret = $this->Gallery->_alter($q);
			if(!$ret) {
				$status = 0;
			}else{
				foreach($src as $item) {
					$path = $_SERVER['DOCUMENT_ROOT']."/userfiles/gallery/{$item["gallery_id"]}/{$item["src"]}";
					$path_t = $_SERVER['DOCUMENT_ROOT']."/userfiles/gallery/{$item["gallery_id"]}/thumb/{$item["src"]}";
					$path_t2 = $_SERVER['DOCUMENT_ROOT']."/userfiles/gallery/{$item["gallery_id"]}/thumb/{$item["thumbnail"]}";
					unlink($path);
					unlink($path_t);
					unlink($path_t2);
				}
			}
		}
		header("X-GalleryItemDelete-Status: $status");
	}
	
	public function item_set_cover($id) {
		$status = 0;
		if($id) {
			$this->Gallery->table_index = 1;
			$this->Gallery->order = "position";
			$this->Gallery->order_direction = "ASC";
			
			$gallery_id = $this->Gallery->findOne("gallery_id", array("id"=>$id));
			
			$this->Gallery->update(array("cover"=>0), array("gallery_id"=>$gallery_id), 1);
			$this->Gallery->update(array("cover"=>1), array("id"=>$id), 1);
			$status = 1;
		}
		header("X-GalleryItemSetCover-Status: $status");
	}
	
	private function _isValidImage($filename) {
		$ret = preg_match('/\.'.implode('$|\.', $this->extensions).'$/i', $filename) ? true : false;
		return $ret;
	}
	
	private function _isValidVideo($filename) {
		$ret = preg_match('/\.'.implode('$|\.', $this->extensions_video).'$/i', $filename) ? true : false;
		return $ret;
	}
	
	private function _prepareFilename(&$f) {
		$latins = array(
			"š" => "s",
			"Š" => "S",
			"č" => "c",
			"Č" => "C",
			"ć" => "c",
			"Ć" => "C",
			"ž" => "z",
			"Ž" => "Z",
			"đ" => "dj",
			"Đ" => "DJ"
		);
		foreach($latins as $k=>$v) {
			$f = str_replace($k,$v,$f);
		}
		$f = str_replace(" ","_",$f);
		$f = strtolower($f);
	}
	
}

?>